﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DotNet.Random.IdCard
{
    /// <summary>
    /// 18位身份证号最后一位随机类，实现了接口IStringRandService
    /// </summary>
    public class IdCardLastLetterRandService : Interface.IStringRandService
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="IdCardLastLetterRandService" /> class.
        /// </summary>
        /// <param name="id">The id.</param>
        /// <exception cref="System.ArgumentNullException">id is null</exception>
        public IdCardLastLetterRandService(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                throw new ArgumentNullException("id is null");
            }
            this.IdCard = id;
        }

        /// <summary>
        /// Gets or sets the id card.
        /// 前17位身份证号
        /// </summary>
        /// <value>
        /// The id card.
        /// </value>
        public string IdCard { get; set; }

        /// <summary>
        /// Rands this instance.
        /// 随机生成字符串方法
        /// 映射到虚方法中，扩展时，可重写
        /// </summary>
        /// <returns>
        /// 返回字符串类型
        /// </returns>
        public virtual string Rand()
        {
            var ai = this.IdCard.ToCharArray();
            var wi = new List<int>() { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1 };
            var sum = 0;
            for (int i = 0; i < ai.Length; i++)
            {
                var temp = int.Parse(ai[i].ToString());
                sum += (temp * wi[i]);
            }
            var mod = sum % 11;
            var aiCheck = new List<string>() { "1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2" };
            var res = aiCheck[mod];
            return res;
        }
    }
}
